import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:netstorage/dao/home_dao.dart';
import 'package:netstorage/model/CommonModel.dart';
import 'package:netstorage/model/grid_nav.dart';
import 'package:netstorage/model/home_config.dart';
import 'package:netstorage/model/home_model.dart';
import 'package:netstorage/pages/search_page.dart';
import 'package:netstorage/utils/navigator_utils.dart';
import 'package:netstorage/dao/login_dao.dart';
import 'package:netstorage/utils/view_utils.dart';
import 'package:netstorage/widget/banner_widget.dart';
import 'package:netstorage/widget/grid_nav_widget.dart';
import 'package:netstorage/widget/loading_container.dart';
import 'package:netstorage/widget/local_nav_widget.dart';
import 'package:netstorage/widget/sales_box_widget.dart';
import 'package:netstorage/widget/search_bar_widget.dart';
import 'package:netstorage/widget/sub_nav_widget.dart';

const searchBarDefaultText = '网红打开 酒店 美食';

class Home extends StatefulWidget {
  static HomeConfig? homeConfig;
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin {
  bool _loading = true;// 全局进度条，默认正在加载

  // 新增首页实体类后新增的成员变量
  // 视频教程中使用如下方法
  // List<CommonModel> bannerList = [];
  // List<CommonModel> localNavList = [];
  // List<CommonModel> subNavList = [];
  // GridNav? gridNav;
  // SalesBox? salesBox;
  // 被我替换为使用下面方法
  HomeModel? homeModel;

  //#region 立即数测试数据
  final Map<String,dynamic> config = {'searchUrl':'https://xdfznh.club/kb/develop/language/java/01.%E5%9F%BA%E7%A1%80/01.%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.html'};
  final Map<String,dynamic> banner01 = {'icon':'https://xdfznh.club/kbp/material/banners/flutter_banner01.png','title':'第一个banner','url':'www.baidu.com'};
  final Map<String,dynamic> banner02 = {'icon':'https://xdfznh.club/kbp/material/banners/flutter_banner02.png','title':'第二个banner','url':'www.sina.com.cn'};
  final Map<String,dynamic> banner03 = {'icon':'https://o.devio.org/images/fa/photo-1601513041797-a79a526a521e.webp','title':'第三个banner','url':'https://juejin.cn/post/7116674718077288485'};
  final Map<String,dynamic> banner04 = {'icon':'https://o.devio.org/images/other/as-cover.png','title':'第四个banner','url':'https://www.moxingshu.cn/article/685cfbf0f163687cdfaafd59'};
  final Map<String,dynamic> banner05 = {'icon':'https://xdfznh.club/kbp/material/banners/flutter_banner03.png','title':'第五个banner','url':'https://www.geekailab.com/io/tools/json-to-dart/'};
  late List<Map<String,dynamic>> bannerList = [banner01,banner02,banner03,banner04,banner05];
  late HomeModel homeModel11 = HomeModel.fromJson({
    'config':config ?? {},'bannerList':(bannerList as List?)?.cast<Map<String,dynamic>>() ?? []
  });
  //#endregion

  //#region 第一次演示单url参数
  // final bannerImgUrlList = [
  //   "https://xdfznh.club/kbp/material/banners/flutter_banner01.png",
  //   "https://xdfznh.club/kbp/material/banners/flutter_banner02.png",
  //   "https://o.devio.org/images/fa/photo-1601513041797-a79a526a521e.webp",
  //   "https://o.devio.org/images/other/as-cover.png",
  //   "https://xdfznh.club/kbp/material/banners/flutter_banner03.png",
  // ];
  //#endregion

  get _logoutBtn => TextButton(
      onPressed: (){
        LoginDao.logout();
        NavigatorUtils.logout();
      },
      child: const Text('退出', style: TextStyle(fontSize: 16, color: Colors.white),)
  );

  //#region appbar 透明度
  double appBarAlpha = 0;
  static const appbarScrollOffset = 100;// appbar 从不透明到透明的滚动距离
  // get _appBar => Opacity(
  //     opacity: appBarAlpha,
  //     child: Container(
  //       height: 80, decoration: const BoxDecoration(color: Colors.white),
  //       child: const Center(
  //         child: Padding(
  //             padding: EdgeInsets.only(top: 20),
  //             child: Text('首页')
  //         ),
  //
  //       )
  //     )
  // );

  get _appBar {
    // 获取屏幕刘海的高度，app的实际内容从刘海下面开始
    double top = MediaQuery.of(context).padding.top;
    return Column(
      children: [
        shadowWrap(child: Container(
          padding: EdgeInsets.only(top: top),
          height: 60 + top,// 60 = 搜索框的高度
          decoration: BoxDecoration(
            color: Color.fromARGB((appBarAlpha * 255).toInt(),255,255,255),
          ),
          child: SearchBarWidget(
            searchBarType: appBarAlpha > 0.2 ? SearchBarType.homeLight : SearchBarType.home,
            inputBoxClick: _jump2Search,
            defaultText: searchBarDefaultText,
            rightBtnClick: (){
              LoginDao.logout();
            },
          ),
        )),
        Container(
          height: appBarAlpha > 0.2 ? 0.5 : 0,
          decoration: BoxDecoration(boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]),
        )
      ],
    );
  }

  get _refreshBtn => MaterialButton(
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
    height: 45,
    onPressed: (){
    _reqData();
    },
    disabledColor: Colors.white60,
    color: Colors.orange,
    child: Text('刷新首页数据', style: TextStyle(color: Colors.white, fontSize: 16)),
  );


  get _listView => ListView(
    children: [
      BannerWidget(bannerList: homeModel?.bannerList ?? []),
      LocalNavWidget(localNavList: homeModel?.localNavList ?? []),
      if(homeModel?.gridNav != null) GridNavWidget(gridNav: homeModel?.gridNav),
      SubNavWidget(subNavList: homeModel?.subNavList),
      if(homeModel?.salesBox != null) SalesBoxWidget(salesBox: homeModel?.salesBox,),
      // _refreshBtn,
      _logoutBtn,
      Text(homeModel?.gridNav?.flight?.item1?.title ?? ''),
      const SizedBox(
        height: 800,
        child: ListTile(
          title: Text('haha'),
        ),
      )
    ],
  );
  //#endregion

  @override
  void initState(){
    super.initState();
    _refreshPage();
  }

  get _refreshContentView => RefreshIndicator(
    color: Colors.blue,
    onRefresh: _refreshPage,
    child: NotificationListener(
      child: _listView,
      onNotification: (scrollNotification){
        if(scrollNotification is ScrollUpdateNotification && scrollNotification.depth == 0){
          _onScroll(scrollNotification.metrics.pixels);
        }
        return false;// 不消费掉滚动事件
      },
    )
  );

  get _contentView => MediaQuery.removePadding(
    removeTop: true, // MediaQuery.removePadding#removeTop 移除顶部为灵动岛预留的留白空间
    context: context,
    child: _refreshContentView,
  );

  @override
  Widget build(BuildContext context) {
    super.build(context);
    NavigatorUtils.updateContext(context);
    return Scaffold(
      backgroundColor: const Color(0xfff2f2f2),
      body: LoadingContainer(
          child: Stack(children: [ _contentView, _appBar ]),
          isLoading: _loading,
          cover: false),
    );
  }

  @override
  bool get wantKeepAlive => true;

  void _onScroll(double offset){
    double alpha = offset / appbarScrollOffset;
    if(alpha < 0) alpha = 0;
    if(alpha > 1) alpha = 1;
    setState(() {
      appBarAlpha = alpha;
    });
  }

  // Future<void> _handleRefresh() async {
  //   try{
  //     HomeModel data = await HomeDao.fetch();
  //     setState(() {
  //       Home.homeConfig = data.config;
  //       homeModel = data;
  //     });
  //   }catch(e){
  //     debugPrint(e.toString());
  //   }
  // }

  HomeModel _mockData(){
    HomeConfig config = HomeConfig.fromJson({'searchUrl':'https://xdfznh.club/kb/develop/language/java/01.%E5%9F%BA%E7%A1%80/01.%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.html'});
    List<CommonModel> bannerList = [];
    CommonModel banner01 = CommonModel.fromJson({'icon':'https://xdfznh.club/kbp/material/banners/flutter_banner01.png','title':'第一个banner','url':'www.baidu.com'});
    CommonModel banner02 = CommonModel.fromJson({'icon':'https://xdfznh.club/kbp/material/banners/flutter_banner02.png','title':'第二个banner','url':'www.sina.com.cn'});
    CommonModel banner03 = CommonModel.fromJson({'icon':'https://o.devio.org/images/fa/photo-1601513041797-a79a526a521e.webp','title':'第三个banner','url':'https://juejin.cn/post/7116674718077288485'});
    CommonModel banner04 = CommonModel.fromJson({'icon':'https://o.devio.org/images/other/as-cover.png','title':'第四个banner','url':'https://www.moxingshu.cn/article/685cfbf0f163687cdfaafd59'});
    CommonModel banner05= CommonModel.fromJson({'icon':'https://xdfznh.club/kbp/material/banners/flutter_banner03.png','title':'第五个banner','url':'https://www.geekailab.com/io/tools/json-to-dart/'});
    bannerList.add(banner01);
    bannerList.add(banner02);
    bannerList.add(banner03);
    bannerList.add(banner04);
    bannerList.add(banner05);

    HomeModel ret = HomeModel.empty();
    ret.config = config;
    ret.bannerList = bannerList;
    return ret;
  }

  Future<void> _refreshPage() async {
    await _reqData();
  }
  _reqData() async {
    try{
      setState(() {
        _loading = true;
      });
      HomeModel data = await HomeDao.fetch();
      setState(() {
        homeModel = data;
      });
    }catch(e){
      print('请求首页数据出现异常：$e');
    }finally{
      setState(() {
        _loading = false;
      });
    }
  }

  void _jump2Search() {
    NavigatorUtils.push(context, SearchPage());
  }








// class _HomeState end
}
